package com.example.demo_dongruanD.service.impl;

import com.example.demo_dongruanD.dto.OrderDetailRequestDto;
import com.example.demo_dongruanD.dto.OrderResponseDto;
import com.example.demo_dongruanD.dto.RequestDto;
import com.example.demo_dongruanD.pojo.Orders;
import com.example.demo_dongruanD.pojo.Users;
import com.example.demo_dongruanD.pojo.Setmeal;
import com.example.demo_dongruanD.pojo.Hospital;
import com.example.demo_dongruanD.repository.OrdersRepository;
import com.example.demo_dongruanD.repository.UsersRepository;
import com.example.demo_dongruanD.repository.SetmealRepository;
import com.example.demo_dongruanD.repository.HospitalRepository;
import com.example.demo_dongruanD.service.OrdersService;
import com.example.demo_dongruanD.response.ApiResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
@Transactional
public class OrdersServiceImpl implements OrdersService {

    @Autowired
    OrdersRepository ordersRepository;

    @Autowired
    UsersRepository usersRepository;

    @Autowired
    SetmealRepository setmealRepository;

    @Autowired
    HospitalRepository hospitalRepository;

    @Override
    public ApiResponse<OrderResponseDto> listOrders(RequestDto requestDto) {
        Integer docId = requestDto.getDocId();
        if (docId == null) {
            return new ApiResponse<>(400, "Bad Request: docId is missing");
        }

        // 查询订单列表
        List<Orders> orders = ordersRepository.findByDocId(docId);

        // 查询关联的用户、套餐和医院信息
        List<Users> users = usersRepository.findByUserIdIn(orders.stream().map(Orders::getUserId).collect(Collectors.toList()));
        List<Setmeal> setmeal = setmealRepository.findBySmIdIn(orders.stream().map(Orders::getSmId).collect(Collectors.toList()));
        List<Hospital> hospitals = hospitalRepository.findByHpIdIn(orders.stream().map(Orders::getHpId).collect(Collectors.toList()));

        // 构建返回给前端的数据结构
        List<Object> dataList = buildDataList(users, orders, setmeal, hospitals);
        return new ApiResponse<>(200, "Success", new OrderResponseDto(dataList, orders.size()), orders.size());
    }

    @Override
    public OrderResponseDto listOrdersDetail(OrderDetailRequestDto requestDto) {
        // 根据条件查询订单列表
        List<Orders> orders = ordersRepository.findAllByConditions(
                (requestDto.getUserId() != null && !requestDto.getUserId().isEmpty()) ? requestDto.getUserId() : null,
                (requestDto.getRealName() != null && !requestDto.getRealName().isEmpty())? requestDto.getRealName() : null,
                requestDto.getSex(),
                requestDto.getSmId(),
                (requestDto.getOrderDate() != null && !requestDto.getOrderDate().isEmpty()) ? requestDto.getOrderDate() : null,
                requestDto.getState(),
                requestDto.getDocId()
        );

        // 查询关联的用户、套餐和医院信息
        List<Users> users = usersRepository.findByUserIdIn(orders.stream().map(Orders::getUserId).collect(Collectors.toList()));
        List<Setmeal> setmeal = setmealRepository.findBySmIdIn(orders.stream().map(Orders::getSmId).collect(Collectors.toList()));
        List<Hospital> hospitals = hospitalRepository.findByHpIdIn(orders.stream().map(Orders::getHpId).collect(Collectors.toList()));

        // 构建返回给前端的数据结构
        List<Object> dataList = buildDataList(users, orders, setmeal, hospitals);
        return new OrderResponseDto(dataList, orders.size());
    }

    // 将查询到的用户、订单、套餐、医院信息整合到一个列表中
    private List<Object> buildDataList(List<Users> users, List<Orders> orders, List<Setmeal> setmeal, List<Hospital> hospitals) {
        List<Object> dataList = new ArrayList<>();

        // 遍历所有订单，确保每个订单都被处理
        for (Orders order : orders) {
            // 查询对应的用户、套餐、医院
            Users user = findUserById(users, order.getUserId());
            if (user == null) {
                continue;
            }
            Setmeal meal = findSetmealById(setmeal, order.getSmId());
            Hospital hospital = findHospitalById(hospitals, order.getHpId());

            // 构建订单详细信息
            Map<String, Object> orderDetails = new HashMap<>();
            orderDetails.put("orderId", order.getOrderId());
            orderDetails.put("userId", user.getUserId());
            orderDetails.put("userName", user.getRealName());
            orderDetails.put("setmealId", meal.getSmId());
            orderDetails.put("setmealName", meal.getName());
            orderDetails.put("hospitalId", hospital.getHpId());
            orderDetails.put("state", order.getState()); // 添加订单状态字段
            orderDetails.put("sex", user.getSex()); // 添加用户性别字段
            orderDetails.put("hospitalName",hospital.getName());//添加医院的名称
            orderDetails.put("orderDate", order.getOrderDate()); // 添加订单日期字段

            dataList.add(orderDetails);
        }

        return dataList;
    }

    // 根据用户ID从用户列表中查找用户
    private Users findUserById(List<Users> users, String userId) {
        return users.stream()
                .filter(user -> userId.equals(user.getUserId()))
                .findFirst()
                .orElse(null); // 或者抛出异常，根据实际需求处理
    }

    // 根据套餐ID从套餐列表中查找套餐
    private Setmeal findSetmealById(List<Setmeal> setmeals, Integer smId) {
        return setmeals.stream()
                .filter(setmeal -> smId.equals(setmeal.getSmId()))
                .findFirst()
                .orElse(null); // 或者抛出异常，根据实际需求处理
    }

    // 根据医院ID从医院列表中查找医院
    private Hospital findHospitalById(List<Hospital> hospitals, Integer hpId) {
        return hospitals.stream()
                .filter(hospital -> hpId.equals(hospital.getHpId()))
                .findFirst()
                .orElse(null); // 或者抛出异常，根据实际需求处理
    }



    @Override
    public void updateOrderState(Integer orderId) {
        Orders order = ordersRepository.findById(orderId)
                .orElseThrow(() -> new IllegalArgumentException("Order not found with id: " + orderId));

        // Update the state to 2 (or any other desired state)
        order.setState(2);

        // Save the updated order back to the database
        ordersRepository.save(order);
    }
}
